package cn.wzy.utils;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ClassUtils {
    /**
     * 获取一个包下面的所有类全限定名
     * @param packageName 包
     * @return
     */
    public static List<Class> getAllClassName(String packageName){
        // 包相对路径
        String packagePath = packageName.replace(".","/"); //把包路径中的点替换为目录
        // 资源URL
        URL url = ClassLoader.getSystemResource(""); //获取classapth
        File[] files = new File(url.getPath() + packagePath) //获取classapth+packagePath,就是完整的路径
                .listFiles(file -> file.getName().endsWith(".class"));

        List<Class> result = new ArrayList<>();
        for(File file : files){
            // 输出类名称
            String fileName = file.getName();
            fileName = fileName.substring(0,fileName.lastIndexOf("."));

            //全限定类名
            String allName = packageName+"."+fileName;
            try {
                result.add(Class.forName(allName));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /*
     * controller中对方法中url的处理
     * */
    public static String methodUrl(Method method, String parentUrl){
        String url = parentUrl;
//        判断方法是什么请求
        GetMapping getMapping = method.getAnnotation(GetMapping.class);
        PostMapping postMapping = method.getAnnotation(PostMapping.class);
        DeleteMapping deleteMapping = method.getAnnotation(DeleteMapping.class);
        PatchMapping patchMapping = method.getAnnotation(PatchMapping.class);
        if (Objects.nonNull(getMapping)&&getMapping.value().length>0){
            url+=getMapping.value()[0];
        }if (Objects.nonNull(postMapping)&&postMapping.value().length>0){
            url+=postMapping.value()[0];
        }if (Objects.nonNull(deleteMapping)&&deleteMapping.value().length>0){
            url+=deleteMapping.value()[0];
        }if (Objects.nonNull(patchMapping)&&patchMapping.value().length>0){
            url+=patchMapping.value()[0];
        }
        return url;
    }
}
